package security.beans;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.application.FacesMessage;  
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;  
import javax.servlet.http.HttpSession;
import login.beans.ConectionBean;
import org.primefaces.event.ToggleEvent;  
import org.primefaces.model.DualListModel;
import security.DAO.UserDAO;
import security.business.RolBusiness;
import security.business.UserBusiness;
/**
 *
 * @author JuanFelipe
 */
@ManagedBean (name = "createUser")
@ViewScoped
public class CreateUserBean {
    
    private boolean lock, expires;
    private String name, authentication, defaultTableSpace,
                   temporaryTableSpace, profile, authentication2,
                   tauthentication;
    private int identified;
    private Map<String,String> tablespace, autenticacion;
            
    private DualListModel< String > privileges;
    
    Connection conn;

    public CreateUserBean() {
        FacesContext context = javax.faces.context.FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        ConectionBean conectionBean =(ConectionBean) session.getAttribute("conectionBean");
        conn = conectionBean.currentConnection;
        name = "C##";
        tablespace = new TreeMap<>();
        autenticacion = new TreeMap<>();
        init();
    }
    
    
    public void handleToggle(ToggleEvent event) {  
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Fieldset Toggled", "Visibility:" + event.getVisibility());  
  
        FacesContext.getCurrentInstance().addMessage(null, msg);  
    }

    public DualListModel<String> getPrivileges() {
        return privileges;
    }

    public void setPrivileges(DualListModel<String> privileges) {
        this.privileges = privileges;
    }

    
    public boolean isLock() {
        return lock;
    }

    public void setLock(boolean lock) {
        this.lock = lock;
    }

    public boolean isExpires() {
        return expires;
    }

    public void setExpires(boolean expires) {
        this.expires = expires;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthentication() {
        return authentication;
    }

    public void setAuthentication(String authentication) {
        System.out.println("->>>>>>>>"+authentication);
        this.authentication = authentication;
    }

    public String getDefaultTableSpace() {
        return defaultTableSpace;
    }

    public void setDefaultTableSpace(String defaultTableSpace) {
        this.defaultTableSpace = defaultTableSpace;
    }

    public String getTemporaryTableSpace() {
        return temporaryTableSpace;
    }

    public void setTemporaryTableSpace(String temporaryTableSpace) {
        this.temporaryTableSpace = temporaryTableSpace;
    }

    public Map<String, String> getAutenticacion() {
        return autenticacion;
    }

    public void setAutenticacion(Map<String, String> autenticacion) {
        this.autenticacion = autenticacion;
    }
    
    
    
    public String getProfile() {
        return profile;
    }

    public void setProfile(String profile) {
        this.profile = profile;
    }

    public int getIdentified() {
        return identified;
    }

    public void setIdentified(int identified) {
        this.identified = identified;
    }

    public Map<String, String> getTablespace() {
        return tablespace;
    }

    public void setTablespace(Map<String, String> tablespace) {
        this.tablespace = tablespace;
    }

    public String getAuthentication2() {
        return authentication2;
    }

    public void setAuthentication2(String authentication2) {
        this.authentication2 = authentication2;
    }

    public String getTauthentication() {
        return tauthentication;
    }

    public void setTauthentication(String tauthentication) {
        this.tauthentication = tauthentication;
    }
    
    
    public void crear(){
        UserDAO udao = new UserDAO( conn );
        System.out.println("Aut: " + authentication);
        System.out.println("NAME: " + name);
        if( tauthentication.equals("password")  ){
            if( authentication==null || !authentication.equals(authentication2)){
                FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_WARN,
                    "Error en Contraseñas",
                    "Las contraseñas no coinciden"));
                return;
            }
        }
        System.out.println("identif: "+ identified);
        try {
            udao.createUser(name, identified, authentication, defaultTableSpace, temporaryTableSpace, new ArrayList<String>(), new ArrayList<String>(), profile, expires, ((lock)?1:0), true, 0);
            
            String sql;
            
            List< String >aux = privileges.getTarget();
            
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO,
                    "Operacion Exitosa!",
                    "usuario creado"));
            
            for( String s : aux){
                sql = "grant "+s +" to \""+name+"\" ";
                try{
                    System.out.println("SQL: "+sql);
                    udao.executeStatement(sql);
                } catch (SQLException ex) {
                    FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_FATAL,
                    "Error Al asignar privilegio!",
                    "privilegio no creado "+ s + " : "+ex.getMessage()));
                }
            }
            
        } catch (SQLException ex) {
            System.out.println("MENS: "+ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_FATAL,
                    "Error Al crear!",
                    "usuario no creado "+ex.getMessage()));
        } catch (Exception e){
            System.out.println("MENS: "+e.getMessage());
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_WARN,
                    "Error Al crear!",
                    "usuario no creado "+e.getMessage()));
        }
    }

    private void init() {
        UserBusiness ub = new UserBusiness(conn);
        
        List<String> aux = new ArrayList<>();
        aux.add("Contraseña");
        aux.add("Externa");
        aux.add("Global");
        
        autenticacion.put("Contraseña", "password");
        autenticacion.put("Externa", "externally");
        autenticacion.put("Global", "globally");
        
        List< String > privSource = initPrivileges();
        List< String > privTarget = new ArrayList<>();
        privileges = new DualListModel<>(privSource, privTarget);
        
        try {
            aux = ub.getTableSpaceName();
            for( String s:aux ){
                System.out.println("TS: "+s);
                tablespace.put(s, s);
            }
        } catch (SQLException ex) {
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_WARN,
                    "Error Al cargar datos!",
                    "datos no cargados"));
        }
        
    }
    
    public void handleChange() {  
        
        if(tauthentication !=null && !tauthentication.equals(""))  {
            
            if( tauthentication.equals("password") ){
                identified = 1;
            }else if( tauthentication.equals("externally") ){
                identified = 2;
            }else if( tauthentication.equals("globally") ){
                identified = 4;
            }
            
        } else  { 
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_WARN,
                    "Please Try Again!",
                    ""));
        }
    }
    
    public ArrayList<String> initPrivileges() {
        FacesMessage msg = new FacesMessage();  
          
        ArrayList<String> res = new ArrayList<>();
        try {
            
            res = new RolBusiness( conn ).getPrivileges();
            
            msg.setSeverity(FacesMessage.SEVERITY_INFO);  
            //msg.setSummary("Privilegios");
            //msg.setDetail("Mostrados Exitosamente");  
            //FacesContext.getCurrentInstance().addMessage(null, msg);  
            return res;
        } catch (SQLException ex) {
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);  
            msg.setSummary("ERROR!");
            msg.setDetail("Fallo al cargar privilegios "+ex);  
            FacesContext.getCurrentInstance().addMessage(null, msg);  
        }
        return res;
    }
}
